<?php

/**
 * @author      :   QuangLT
 * @name        :   Plun_Plugin_Auth
 * @version     :   1.0
 * @copyright   :   Plun-Asia
 * @todo        :   Acl plugin
 */
class Plun_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $except = array(
            array(
                'module' => 'default',
                'controller' => 'user',
                'action' => 'login'
            ),
            array(
                'module' => 'default',
                'controller' => 'user',
                'action' => 'signup'
            ),
            array(
                'module' => 'default',
                'controller' => 'user',
                'action' => 'check-register'
            )
        );

        $params = array(
            'module' => strtolower($request->getModuleName()),
            'controller' => strtolower($request->getControllerName()),
            'action' => strtolower($request->getActionName())
        );

        if (in_array($params, $except)) {
            return true;
        }

        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();

            define('UID', $identity['user_id']);
            define('USER_NAME', $identity['user_name']);
            define('USER_EMAIL', $identity['user_email']);
            define('USER_ROLE', $identity['user_role']);

//            if (USER_ROLE == 1 && !in_array($params['module'], array('advertiser', 'default'))) {
//                Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->gotoUrl("/advertiser");
//            } else if (USER_ROLE == 2 && !in_array($params['module'], array('publisher', 'default'))) {
//                Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->gotoUrl("/publisher");
//            } else if (USER_ROLE == 4 && !in_array($params['module'], array('agency', 'default'))) {
//                Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->gotoUrl("/agency");
//            } else if (USER_ROLE == 3 && !in_array($params['module'], array('advertiser', 'publisher', 'default'))) {
//                Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->gotoUrl("/advertiser");
//            }

        } else { //if ($params['module'] !== 'default') {
            //Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->gotoUrl("user/login/#" . $_SERVER['REQUEST_URI']);
        }

        /**
         * Assign request for view
         */

        Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view')->assign('request', $request);
    }
}